package com.example.springbootjsp.controller;

import cn.hutool.core.io.FileUtil;
import com.example.springbootjsp.entities.FileInfo;
import com.google.common.collect.Lists;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.io.File;
import java.util.List;

/**
 * @author : zhangrenren
 * @description : TODO
 * @date : 6/30/2020 10:37 AM
 */
@Controller
@RequestMapping("/preview")
public class PreviewController {

    private static final Logger LOGGER = LoggerFactory.getLogger(PreviewController.class);

    @RequestMapping("/column/{columnName}")
    public String previewColumnName(@PathVariable("columnName") String columnName, Model model) {
        // 通过要预览的栏目名称来拼接栏目地址
        String columnPath = "static/files/" + columnName + "/";
        // 获取栏目地址下面的所有文件
        List<FileInfo> fileInfos = Lists.newArrayList();
        fileInfos = getFileInfos(columnPath);
        model.addAttribute("column",columnName);
        model.addAttribute("fileInfos",fileInfos);
        return "visit_files";
    }

    @RequestMapping("/pdfH5")
    public String pdfH5View(@RequestParam("column") String column,
                            @RequestParam("fileName") String fileName,
                            Model model) {
        model.addAttribute("column",column);
        model.addAttribute("name",fileName);
        return "view";
    }

    private static List<FileInfo> getFileInfos(String path) {
        // 1. 首先判断文件夹是否存在,不存在则创建文件夹
        FileUtil.mkdir(path);
        List<FileInfo> fileInfos = Lists.newArrayList();
        File[] tempList = FileUtil.ls(path);
        if ( tempList != null ) {
            // 文件非空
            for (int i = 0; i < tempList.length; i++) {
                if (tempList[i].isFile()) {
                    String nameWithType = FileUtil.getName(tempList[i]);;
                    String name = FileUtil.mainName(nameWithType);
                    FileInfo fileInfo = new FileInfo();
                    fileInfo.setName(name);
                    fileInfo.setNameWithType(nameWithType);
                    fileInfos.add(fileInfo);
                }
                if (tempList[i].isDirectory()) {
                    // 文件夹下子目录的文件就不递归了.
                }
            }
        }
        return fileInfos;
    }

}
